import { login, logout } from "@/api/user";
import AdminController from "@/api/controller/AdminController";
// import { jsonInBlacklist } from "@/api/jwt";
import router, { getUserRouter, resetRouter } from "@/router/index";
// import Vue from "vue";
import { getRolesList, cutover } from "../../api/systemManage/userManage";
import dbl from "@/utils/dbl";
import permission from "./permission";
import Base64 from "base-64";
import AES from "@/utils/cryptoJS"
export const user = {
  namespaced: true,
  state: {
    userInfo: "" || dbl.get("userInfo"),
    rolesInfo: "",
    token: "",
    rolesList: ""|| dbl.get("rolesList"),
    orgInfo: "",
    role: null,
    levelID: null,
    currentUserInfo:""|| dbl.get("currentUserInfo"),
    localPageSteps:""|| dbl.get("localPageSteps")
  },
  mutations: {
    setRolesList(state, rolesList) {
      rolesList = AES.encrypt(JSON.stringify(rolesList))
      state.rolesList = rolesList;
      dbl.set("rolesList", rolesList);
      // console.log('state.userInfo',state.userInfo)
      // state.userInfo = { ...dbl.get("userInfo"), realName: rolesList.realName };
      // console.log('setRolesList', rolesList)
    },
    setRolesInfo(state, rolesInfo) {
      // sessionStorage.clear();
      rolesInfo = Base64.encode(rolesInfo)
      state.rolesInfo = rolesInfo;
      dbl.set("rolesInfo", rolesInfo);
    },
    setUserInfo(state, userInfo) {
      // 这里的 `state` 对象是模块的局部状态
      let userInfo1 = AES.encrypt(JSON.stringify(userInfo))
      state.userInfo = userInfo1;
      dbl.set("userInfo", userInfo1);
    },
    setCurrentUserInfo(state, currentUserInfo) { // 查看下一级个人信息存储
      // 这里的 `state` 对象是模块的局部状态
      currentUserInfo = AES.encrypt(JSON.stringify(currentUserInfo))
      state.currentUserInfo = currentUserInfo;
      dbl.set("currentUserInfo", currentUserInfo);
    },
    setLocalPageSteps(state, localPageSteps) {
      // 这里的 `state` 对象是模块的局部状态
      localPageSteps = AES.encrypt(JSON.stringify(localPageSteps))
      state.localPageSteps = localPageSteps;
      dbl.set("localPageSteps", localPageSteps);
    },
    setOrgInfo(state, orgInfo) {
      // 这里的 `state` 对象是模块的局部状态
      state.orgInfo = orgInfo;
      dbl.set("orgInfo", orgInfo);
    },
    setRole(state, role) {
      // 这里的 `state` 对象是模块的局部状态
      state.role = role;
      dbl.set("role", role);
    },
    setToken(state, token) {
      // 这里的 `state` 对象是模块的局部状态
      state.token = token;
      dbl.set("token", token);
    },
    // NeedInit(state) {
    //   state.userInfo = {};
    //   state.token = "";
    //   sessionStorage.clear();
    //   router.push({ name: "init", replace: true });
    // },
    async LoginOut(state) {
     await sessionStorage.clear();

      // utils.isWxwork
      // ? window.location.replace(utils.oauth2Url)
      // : window.location.replace(utils.saomaUrl);
      setTimeout(() => {
        // router.push({ name: "login", replace: true });
        window.location.reload();
      }, 1000);

      // window.location.href = process.env.VUE_APP_BASE_URL;
      // router.push({ name: "login" });
    },
    ResetUserInfo(state, userInfo = {}) {
      state.userInfo = { ...state.userInfo, ...userInfo };
    },
  },
  actions: {
    // 正常登陆
    async LoginIn({ commit, dispatch, rootGetters, getters }, loginInfo) {
      let res = await login(loginInfo);
      // console.log("login res", res);
      if (res.code == 0) {
        sessionStorage.clear();
        let rolesInfo = "";
        rolesInfo = (res.data.org?.name || "") + (res.data.role?.name || "");
        commit("setUserInfo", res.data.user);
        commit("setToken", res.data.token);
        commit("setRolesInfo", rolesInfo);
        commit("setOrgInfo", res.data.org);
        commit("setRole", res.data.role);
        // Vue.ls.set("userInfo", res.data.user, 1 * 24 * 60 * 60 * 1000);
        // Vue.ls.set("token", res.data.token, 1 * 24 * 60 * 60 * 1000);
        // Vue.ls.set("orgInfo", res.data.org, 1 * 24 * 60 * 60 * 1000);
        // Vue.ls.set("rolesInfo", rolesInfo, 1 * 24 * 60 * 60 * 1000);
        // Vue.ls.set("role", res.data.role, 1 * 24 * 60 * 60 * 1000);
        // state.role = res.data.role;
        await dispatch("getRolesList");
        await dispatch("router/SetAsyncRouter", {}, { root: true });
        await dispatch("dictionary/getFindByLevel", {}, { root: true });
        const asyncRouters = rootGetters["router/asyncRouters"];
        router.addRoutes(asyncRouters);

        // const redirect = router.history.current.query.redirect
        // console.log(redirect)
        // if (redirect) {
        //     router.push({ path: redirect })
        // } else {
        router.push({
          name: getters["userInfo"]?.authority?.defaultRouter,
          replace: true,
        });
        // window.location.reload()
        // }
        return true;
      }
    },
    // 重新获取用户信息
    async getMenu({ commit, dispatch, rootGetters, getters }, data) {
        let res = await AdminController.getInfo({ data });
        let body = res.data;
        if (res?.code == 0) {
          let userRouters = getUserRouter(body ? body.menuPermission : "");
          commit("setUserInfo", body);
          await dispatch("permission/setRouters", userRouters, { root: true });
          // commit("permission/SET_ROUTERS", userRouters);
          resetRouter();
        }
    },
    // 退出登陆
    async LoginOut({ commit }, type) {
      commit("LoginOut");
      // if (type && type == 1) {
      //   const res = await logout();
      //   if (res.code == 0) {
      //     commit("LoginOut");
      //   }
      // } else {
      //   commit("LoginOut");
      // }
    },
    // 角色列表获取
    async rolesList({ commit }, data) {
      commit("setRolesList", data);
      // const res = await getRolesList({});
      // let { code, data } = res;
      // if (code == 0) {
      //   commit("setRolesList", data);
      // }
    },
    async changeRoles({ commit, dispatch }, body) {    
      let userRouters = getUserRouter(body ? body.menuPermission : "", body);
      // await dispatch("permission/SET_ROUTERS", userRouters);
      commit("setUserInfo", body);
      commit("setToken", Base64.encode(body.phone));  
      commit("setCurrentUserInfo", "");
      commit("setLocalPageSteps", "");
      resetRouter();
      // dbl.set("localPageSteps", "");
      let menu = userRouters[0].children[0];
      console.log("menu", menu);
      // this.userInfo = body;
      // window.location.reload()
      router.addRoutes(userRouters);
      // router.push({ name:menu.name, query:menu.meta.query , replace: true});
      // window.location.reload()
      router.push({
        name: menu.name,
        query: { ...menu.meta.query, requestId: new Date().getTime() },
        replace: true,
      });
    }
  },
  getters: {
    getRole(state) {
      return state.role ?? dbl.get("role");
    },
    userInfo(state) {
      let userInfo = state.userInfo? AES.decrypt(state.userInfo) : '{}';
      console.log('userInfo', state.userInfo, "",JSON.parse(userInfo))
      return JSON.parse(userInfo);
    },
    rolesInfo(state) {
      return state.rolesInfo || dbl.get("rolesInfo") || "未绑定角色";
    },
    orgInfo(state) {
      return state.orgInfo || dbl.get("orgInfo");
    },
    token(state) {
      return state.token || dbl.get("token");
    },
    detailsInfo(state) {
      return state.detailsInfo;
    },
    rolesList(state) {
      let roleList = state.rolesList? AES.decrypt(state.rolesList) : '[]';
      // console.log('roleList',dbl.get("roleList"),"",JSON.parse(roleList))
      return JSON.parse(roleList)
    },
    currentUserInfo(state) {
      let currentUserInfo = state.currentUserInfo ? JSON.parse(AES.decrypt(state.currentUserInfo)) : '';
      // console.log('currentUserInfo',dbl.get("currentUserInfo"), "",JSON.parse(currentUserInfo))
      return currentUserInfo;
    },
    localPageSteps(state) {
      let localPageSteps = state.localPageSteps ?AES.decrypt(state.localPageSteps) : '[]';
      return JSON.parse(localPageSteps);
    },
  },
};
